import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
// 只在浏览器环境下引入 ElMessage
let ElMessage: any = undefined;
if (typeof window !== 'undefined') {
  // @ts-ignore
  ElMessage = (await import('element-plus')).ElMessage;
}

// 不使用baseURL，因为我们使用完整URL
const service: AxiosInstance = axios.create({
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    console.log('发送请求:', config.url, config.data);
    if (typeof window !== 'undefined') {
      const token = localStorage.getItem('token');
      if (token && config.headers) {
        config.headers['Authorization'] = `Bearer ${token}`;
      }
    }
    return config;
  },
  (error) => {
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    console.log('响应数据:', response.data);
    return response;
  },
  (error) => {
    console.error('响应错误:', error);
    if (typeof window !== 'undefined' && ElMessage) {
      if (error.response && error.response.data && error.response.data.message) {
        ElMessage.error(error.response.data.message);
      } else {
        ElMessage.error('请求出错，请稍后重试');
      }
    }
    return Promise.reject(error);
  }
);

export function get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
  return service.get(url, config).then(res => res.data);
}

export function post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
  return service.post(url, data, config).then(res => res.data);
}

export default service;
